package com.chery.media.ui.music

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.hardware.usb.UsbManager
import android.os.IBinder
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.Utils
import com.chery.media.R
import com.chery.media.contacts.ActionContacts
import com.chery.media.contacts.MusicType
import com.chery.media.library.base.BaseViewModel
import com.chery.media.library.event.SingleLiveEvent
import com.chery.media.library.extend.asResponse
import com.chery.media.library.extend.databind.BooleanObservableField
import com.chery.media.library.extend.toResString
import com.chery.media.library.extend.toast
import com.chery.media.library.network.ResponseThrowable
import com.chery.media.music.BluetoothMusicTool
import com.chery.media.music.MusicService
import com.chery.media.music.OperateMusicType
import com.chery.media.network.model.MusicBean
import com.chery.media.network.model.MusicPlayBean
import com.chery.media.utils.LocalMusicHelper
import com.chery.media.utils.USBBroadcastReceiver
import com.chery.media.utils.appRepository
import kotlinx.coroutines.flow.catch


val musicViewModel: MusicViewModel by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    MusicViewModel()
}

class MusicViewModel : BaseViewModel() {

    val currentType = SingleLiveEvent<MusicType>()

    val usbMusicList = SingleLiveEvent<ArrayList<MusicBean>>()

    val hotMusicList = SingleLiveEvent<ArrayList<MusicBean>>()

    var serviceConnection: ServiceConnection? = null

    val currentPlayMusic = SingleLiveEvent<MusicPlayBean>()

    @SuppressLint("StaticFieldLeak")
    var musicService: MusicService? = null

    var page: Int = 1
        set(value) {
            field = value
            getMusicData()
        }


    val setTypes = arrayListOf<Triple<Int, Int, String>>().apply {
        add(
            Triple(
                R.drawable.svg_bluetooth_un_select,
                R.drawable.svg_bluetooth_selected,
                R.string.bluetooth.toResString()
            )
        )
        add(Triple(R.drawable.svg_usb_un_select, R.drawable.svg_usb_selected, R.string.usb.toResString()))
        add(Triple(R.drawable.svg_hot_un_select, R.drawable.svg_hot_selected, R.string.hot_list.toResString()))
    }

    // 播放状态
    val playStatus = BooleanObservableField()

    fun playMusicById(id: String) {
        val position = hotMusicList.value?.indexOfFirst { it.id == id } ?: -1
        if (position != -1) {
            playMusic(position)
        } else {
            "No music".toast()
        }
    }

    /**
     * 播放音乐
     */
    fun playMusic(position: Int = -1) {
        if (currentType.value == MusicType.BLUETOOTH) {
            BluetoothMusicTool.operateMusic(OperateMusicType.PLAY)
        } else {
            if (position != -1) {
                musicService?.play(position)
            } else {
                musicService?.play()
            }
        }
    }

    /**
     * 播放暂停
     */
    fun playPause() {
        if (currentType.value == MusicType.BLUETOOTH) {
            BluetoothMusicTool.operateMusic(OperateMusicType.PAUSE)
        } else {
            musicService?.playPause()
        }
    }

    /**
     * 播放下一首
     */
    fun playNext() {
        if (currentType.value == MusicType.BLUETOOTH) {
            BluetoothMusicTool.operateMusic(OperateMusicType.NEXT)
        } else {
            musicService?.playNext()
        }
    }

    /**
     * 播放上一首
     */
    fun playPrevious() {
        if (currentType.value == MusicType.BLUETOOTH) {
            BluetoothMusicTool.operateMusic(OperateMusicType.PREVIOUS)
        } else {
            musicService?.playPre()
        }
    }

    /**
     * 设置音乐类型
     */
    fun setMusicType(musicType: MusicType, musicId: String = ""){
        if(currentType.value == MusicType.HOT_LIST && playStatus.get() && musicId.isNullOrEmpty().not()) {
            playMusicById(musicId)
            return
        }
        if (currentType.value == musicType) return
        currentType.value = musicType
        when (musicType) {
            MusicType.BLUETOOTH -> {
//                musicService?.playPause()
//                BluetoothMusicTool.init()
            }
            MusicType.USB -> {
                if (usbMusicList.value.isNullOrEmpty()) {
                    getUsbMusicList(true)
                } else {
                    musicService?.setMusicList(usbMusicList.value ?: arrayListOf(), false)
                    musicService?.play(0)
                }
            }
            else -> {
                if (hotMusicList.value.isNullOrEmpty()) {
                    getMusicData()
                } else {
                    musicService?.setMusicList(hotMusicList.value ?: arrayListOf(), false)
                    if (musicId.isNullOrEmpty()) {
                        musicService?.play(0)
                    } else {
                        playMusicById(musicId)
                    }
                }
            }
        }
    }

    /**
     * 获取U盘音乐列表
     */
    fun getUsbMusicList(isPlay: Boolean = false) {
        launch {
            usbMusicList.value = LocalMusicHelper.getLocalMusics(Utils.getApp())
            if (isPlay) {
                if (usbMusicList.value.isNullOrEmpty()) {
                    "No music".toast()
                }
                musicService?.setMusicList(usbMusicList.value ?: arrayListOf(), false)
                musicService?.play(0)
            }
        }
    }

    // 获取音乐数据
    fun getMusicData() {
        val map = mutableMapOf<String, Any>()
        map["limit"] = "100"
        map["page"] = page
        launch {
            appRepository.getMusicData(map)
                .asResponse()
                .catch { if (it is ResponseThrowable) it.errMsg.toast() }
                .collect {
//                    it.records?.forEach {
//                        it.playPath = "http://music.163.com/song/media/outer/url?id=317151.mp3"
//                    }
                    hotMusicList.value = it.records ?: arrayListOf()
                }
        }
    }

    /**
     * 初始化监听
     */
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    fun initBroad(){
        val usbBroadcastReceiver = USBBroadcastReceiver()
        val usbDeviceStateFilter = IntentFilter()
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        usbDeviceStateFilter.addAction(ActionContacts.ACTION_USB_PERMISSION)
        Utils.getApp().registerReceiver(usbBroadcastReceiver, usbDeviceStateFilter)
    }

    /**
     * 启动音乐服务
     */
    fun startService() {
        serviceConnection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                musicService = (service as MusicService.MusicBinder).getMusicService()
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                musicService = null
            }

        }
        val intent = Intent(Utils.getApp(), MusicService::class.java)
        intent.action = "com.chery.media.music.MusicService"
        Utils.getApp().bindService(intent, serviceConnection!!, AppCompatActivity.BIND_AUTO_CREATE)
    }

    /**
     * 重置
     */
    fun mediaPlayerReset(){
        musicService?.playReset()
    }

    /**
     * 检测蓝牙是否连接
     */
    fun isBluetoothHeadsetConnected(context: Context): Boolean {
        val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
        val bluetoothAdapter = bluetoothManager?.adapter
        return if (bluetoothAdapter != null) {
            val connectedDevices = if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.BLUETOOTH
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                1
            } else bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)
            connectedDevices == BluetoothProfile.STATE_CONNECTED
        } else {
            false
        }
    }

    // 调用这个函数可以打开系统的蓝牙设置页面
    fun openBluetoothSettings(context: Context) {
        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        context.startActivity(intent)
    }

    override fun onCleared() {
        super.onCleared()
        musicService?.playPause()
        if (serviceConnection != null)
            Utils.getApp().unbindService(serviceConnection!!)
        BluetoothMusicTool.unregisterCallback()
    }

}